/**
 * 首页控制器
 */
angular
.module('myApp')
.controller('indexController', function($scope, subjectManager, classManager) {

  subjectManager.getSubjects()
    .then(function(data) {
      $scope.subjects = data;
    }, function(data) {
      $scope.subjects = [];
    });

  $scope.$watch('subjects', function(value) {
    if (angular.isDefined(value)) {
      $scope.subject = value[0];
    };
  });

  $scope.$watch('subject', function(value) {
    if (angular.isDefined(value)) {
      $scope.grades = value.grades;
    };
  });

  $scope.$watch('grades', function(value) {
    if (angular.isDefined(value)) {
      $scope.grade = value[0];
    };
  });

  $scope.$watch('grade', function(value) {
    if (angular.isDefined(value)) {
      $scope.terms = value.terms;
    };
  });

  $scope.$watch('terms', function(value) {
    if (angular.isDefined(value)) {
      $scope.term = value[0];
    };
  });

  $scope.$watch('term', function(value) {
    if (angular.isDefined(value)) {
      classManager.getClasses({
        subject_id: $scope.subject.id,
        grade_id: $scope.grade.id,
        term_id: $scope.term.id
      })
      .then(function(data) {
        $scope.classes = data;
      }, function(data) {
        $scope.classes = [];
      });
    };
  });

  $scope.$watch('classes', function(value) {
    if (angular.isDefined(value)) {
      $scope.class = value[0];
    };
  });

  $scope.subjectClicked = function(subjectId) {
    angular.forEach($scope.subjects, function(el) {
      if (subjectId == el.id) {
        $scope.subject = el;
      }
    });
  }

  $scope.gradeClicked = function(gradeId) {
    angular.forEach($scope.grades, function(el) {
      if (gradeId == el.id) {
        $scope.grade = el;
      }
    });
  }

  $scope.termClicked = function(termId) {
    angular.forEach($scope.terms, function(el) {
      if (termId == el.id) {
        $scope.term = el;
      }
    });
  }

  $scope.classClicked = function(classId) {
    angular.forEach($scope.classes, function(el) {
      if (classId == el.id) {
        $scope.class = el;
      }
    });
  }
});
